package cn.iocoder.yudao.module.system.service.userRole;

import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.system.controller.admin.userRole.vo.*;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.system.convert.userRole.UserRoleConvert;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 用户和角色关联 Service 实现类
 *
 * @author 谭万全
 */
@Service
@Validated
public class UserRoleServiceImpl implements UserRoleService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public Long createUserRole(UserRoleCreateReqVO createReqVO) {
        // 插入
        UserRoleDO userRole = UserRoleConvert.INSTANCE.convert(createReqVO);
        userRoleMapper.insert(userRole);
        // 返回
        return userRole.getId();
    }

    @Override
    public void updateUserRole(UserRoleUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateUserRoleExists(updateReqVO.getId());
        // 更新
        UserRoleDO updateObj = UserRoleConvert.INSTANCE.convert(updateReqVO);
        userRoleMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserRole(Long id) {
        // 校验存在
        this.validateUserRoleExists(id);
        // 删除
        userRoleMapper.deleteById(id);
    }

    private void validateUserRoleExists(Long id) {
        if (userRoleMapper.selectById(id) == null) {
            throw exception(USER_ROLE_NOT_EXISTS);
        }
    }

    @Override
    public UserRoleDO getUserRole(Long id) {
        return userRoleMapper.selectById(id);
    }


    @Override
    public List<UserRoleDO> getUserRoleByUserId(Long userId) {
        UserRolePageReqVO pageReqVO=new UserRolePageReqVO();
        pageReqVO.setUserId(userId);
        return userRoleMapper.selectPage(pageReqVO).getList();
    }

    @Override
    @TenantIgnore
    public UserRoleDO getUserRoleByTenantId(Long userId, Long tenantId) {
        return userRoleMapper.selectOne("tenant_id",tenantId,"user_id",userId);
    }


    @Override
    public List<UserRoleDO> getUserRoleList(Collection<Long> ids) {
        return userRoleMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<UserRoleDO> getUserRolePage(UserRolePageReqVO pageReqVO) {
        return userRoleMapper.selectPage(pageReqVO);
    }

    @Override
    public List<UserRoleDO> getUserRoleList(UserRoleExportReqVO exportReqVO) {
        return userRoleMapper.selectList(exportReqVO);
    }

}
